<?php
namespace app\beautiful\controller\miniapp\member;

use app\BaseController;
use app\beautiful\model\CouponModel;
use app\beautiful\model\GiftbagModel;
use app\beautiful\model\PartnerGiftbagModel;
use app\common\logic\DataLogic;
use app\common\model\ShopPosterModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\partner\PartnerSettingModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\member\MemberModel;
use app\common\logic\TokenLogic;
use app\common\model\ShopModel;
use app\beautiful\model\partner\PartnerWithdrawModel;
use think\facade\Db;
use think\Model;

class Partner extends BaseController{
    protected $partner;
    public function check(){
        $member=$this->request->member;
        $this->partner = PartnerModel::where([
           ['shop_id','=',$this->request->shopId],
           ['mobile','=',$member->mobile],
           ['status','=',1],
           ['is_delete','=',0]
        ])->find();
        if($this->partner === null) return false;
        return true;
    }
    
    public function getPartnerQrCode(){
        $path = $this->request->param('path');
        if(empty($path)){
            $path = '/pages/client/index?pid='.$this->request->memberId;
        }else{
            $path = $path . '&pid='.$this->request->memberId;
        }
        $shop = ShopModel::find($this->request->shopId);
        $t = $this->request->time();
        $sign = md5($this->request->shopId.'|'.$path.'|'.$t.'|'. TokenLogic::getAppQrSignToken());
        if($shop->status == 8){
             $url = $this->request->domain().'/platform/miniapp/qrcodeImg?shop_id='.$this->request->shopId.'&t='.$t.'&path='.urlencode($path).'&sign='.$sign;
        }else{
             $url = $this->request->domain().'/platform/miniapp/testQrcodeImg?shop_id='.$this->request->shopId.'&t='.$t.'&path='.urlencode($path).'&sign='.$sign;
        }
        return $this->success([
          'img' => $url
         ]);
    }
    
    //提现申请
    public function partnerWithdrawAct(){
        $money = $this->request->param('money/f');
        $type = $this->request->param('type/f');
        $partner_type = $this->request->param('partner/f');
        if($money <= 0) return $this->error ('提现金额不能小于等于0');
        $member=$this->request->member;
        Db::startTrans();
        try{
            $partner = PartnerModel::where([
               ['shop_id','=',$this->request->shopId],
               ['mobile','=',$member->mobile],
               ['status','=',1],
               ['is_delete','=',0]
            ])->lock(true)->find();
            if(null === $partner){
                Db::rollback();
                return $this->error ('只有会员推广员才能提现');
            }
//            if($partner->role_id != 3){
//                 Db::rollback();
//                 return $this->error ('只有会员推广员才能提现');
//            }
            if($partner->withdrawable_profit < $money){
                Db::rollback();
                return $this->error('提现金额不能大于可提现的金额');
            }
            $PartnerWithdrawModel = new PartnerWithdrawModel();
            $PartnerWithdrawModel->save([
                'shop_id'       => $this->request->shopId,
                'partner_id'    => $partner->partner_id,
                'open_id'       => $member->open_id,
                'money'         => $money,
                'status'        => 0,
                'type'        => $type,
                'partner_type'        => $partner_type,
            ]);
            $partner->withdrawable_profit = round(($partner->withdrawable_profit  * 100 - $money * 100)/100,2);
            $partner->save();
            Db::commit();
            return $this->success('申请成功，等待到账');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
        
    }
    
    public function getPartnerWithdraw(){
        $partner = $this->request->param('partner/f');
         if($this->check() == false) return $this->error('您还不是推广员');
         $datas = PartnerWithdrawModel::where([
            ['shop_id','=', $this->request->shopId],
            ['partner_id','=', $this->partner->partner_id],
            ['partner_type','=', $partner]
         ])->limit($this->request->limit)->page($this->request->page)->order(['withdraw_id'=>'desc'])->select()->append(['add_day'])->toArray();

         return $this->success([
            'list'=>$datas
        ]); 
    }
    
    public function getPartnerCustomer(){
        if($this->check() == false) return $this->error('您还不是推广员');
        $datas = PartnerCommissionModel::where([
            ['shop_id','=', $this->request->shopId],
            ['partner_id','=', $this->partner->partner_id]
        ])->field('member_id,sum(monetary) as money')->group('member_id')->limit($this->request->limit)->page($this->request->page)->order(['money'=>'desc'])->select();
        $newDatas = [];
        if(!empty($datas)){
            $memberIds = [];
            foreach($datas as $val){
                $memberIds[$val['member_id']] = $val['member_id'];
            }
            $MemberModel = new MemberModel();
            $members = $MemberModel->itemsByIds($memberIds);
            
            foreach($datas as $val){
                $newDatas[] = [
                    'member_id' => $val['member_id'],
                    'money'     => $val['money'],
                    'mobile'    => empty($members[$val['member_id']]) ? '用户已注销' : yc_phone($members[$val['member_id']]['mobile']),
                    'add_time'  => empty($members[$val['member_id']]) ? '-' : date('Y.m.d',$members[$val['member_id']]['add_time'])
                ];
            }
        }
        return $this->success([
            'list'=>$newDatas
        ]);
    }
    
    public function getPartnerCommission(){
        if($this->check() == false) return $this->error('您还不是推广员');
        
        $datas = PartnerCommissionModel::where([
            ['shop_id','=', $this->request->shopId],
            ['partner_id','=', $this->partner->partner_id]
        ])->field('monetary,commission,add_time')->limit($this->request->limit)->page($this->request->page)->order(['commission_id'=>'desc'])->select();
        
        $newDatas = [];
        if(!empty($datas)){
            foreach($datas as $val){
                $newDatas[] = [
                    'monetary'     => $val['monetary'],
                    'commission'   => $val['commission'],
                    'add_time'  => date('Y-m-d H:i',$val['add_time'])
                ];
            }
        }
        return $this->success([
            'list'=>$newDatas
        ]);
    }
    
    public function getPartnerInfo(){
        if($this->check() == false) return $this->error('您还不是推广员');
        $shopData = ShopModel::find($this->request->shopId);
        $info = [
            'partner_id'    => $this->partner->partner_id,
            'role_id'       => $this->partner->role_id,
            'name'          => $this->partner->name,
            'mobile'        => yc_phone($this->partner->mobile),
            'bg_time'       => date('Y-m-d', $this->partner->add_time),
            'expire_time'   => $this->partner->expire_time,
            'share_capital' => $this->partner->share_capital,
            'profit'        => $this->partner->profit,
            'withdrawable_profit' => $this->partner->withdrawable_profit,
            'status'        => $this->partner->status,
            'member_face'   => $this->request->member->face,
            'custom_name'   => $this->partner->custom_name,
            'custom_rate'   => $this->partner->custom_rate,
            'mode'          => $shopData->mode,
            'wechatnum'     => $shopData->wechatnum,
        ];
        if($this->partner->role_id == 1){ //股东
             if(null === $setting = PartnerSettingModel::where([
                 ['shop_id','=', $this->request->shopId]
             ])->find()){
                 return $this->error('推广员配置暂未配置');
             }
             $dividend_ratio_data = $setting->dividend_ratio_data;
             $max = 0;
             foreach($dividend_ratio_data as $val){
                 if($val['share_capital'] <= $this->partner->share_capital){
                     if($val['dividend_ratio'] > $max){
                         $max = $val['dividend_ratio'];
                     } 
                 }
             }
             $info['dividend_ratio'] = $max;
        }
        if($this->partner->role_id == 2){ //员工
            $month = date('Y-m',time());
            $info['monetary'] = PartnerCommissionModel::where([
                ['month','=',$month],
                ['shop_id','=',$this->request->shopId],
                ['partner_id','=', $this->partner->partner_id]
            ])->sum('monetary');
            $info['commission'] = PartnerCommissionModel::where([
                ['month','=',$month],
                ['shop_id','=',$this->request->shopId],
                ['partner_id','=', $this->partner->partner_id]
            ])->sum('commission');
        }
        if($this->partner->role_id == 3){
            $info['child'] = MemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['pid','=', $this->request->memberId]
            ])->count();
        }
        
        return $this->success([
            'info' =>$info
        ]);
    }

    public function getPosterList()
    {
        $datas= ShopPosterModel::where([
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0]
        ])->limit($this->request->limit)
            ->page($this->request->page)
            ->append(['add_time_format'])
            ->select()->toArray();
        return $this->success(['datas'=>$datas]);
    }
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 合伙人礼包列表
     */
    public function getPartnerGiftbagList()
    {
        if($this->check() == false) return $this->error('您还不是推广员');

        $shop_id =  $this->request->shopId;
        $partner_id = $this->partner->partner_id;
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error('合伙人不存在');

        $where=[

            ['shop_id','=',$shop_id],
            ['partner_id','=',$partner_id]

        ];

        $partner_giftbag = new PartnerGiftbagModel();

        $order=['update_time'=>'desc','add_time'=>'desc'];

        $field="partner_id,partner_giftbag_id,giftbag_id,send_qty,remand_qty";

        $append=[];
        $return = DataLogic::getDataList($partner_giftbag,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        $return['new_list'] = [];
        foreach($return['list'] as $giftbag){
            $data['partner_id'] = $giftbag['partner_id'] ;
            $data['partner_giftbag_id'] = $giftbag['partner_giftbag_id'] ;
            $data['giftbag_id'] = $giftbag['giftbag_id'] ;
            $data['name'] = GiftbagModel::where('giftbag_id',$giftbag['giftbag_id'])->value('name');
            $data['send_qty'] = $giftbag['send_qty'] ;
            $data['remand_qty'] = $giftbag['remand_qty'];

            if(null ===  GiftbagModel::find($giftbag['giftbag_id'])) continue;

            $giftbag_coupon_ids = GiftbagModel::where('giftbag_id','=',$giftbag['giftbag_id'])
                ->order($order)->value('coupon_ids');

            //优惠券列表
            $today=date("Y-m-d",$this->request->time());
            $coupon_where[]=['status','=',1];
            $coupon_where[]=['end_time','>=',$today];
            $coupon_where[]=['coupon_id','in',$giftbag_coupon_ids];
            $coupon_order=['update_time'=>'desc','add_time'=>'desc'];

            $giftbag_coupon_name_array = CouponModel::where($coupon_where)->field("coupon_id,name,type_id,valid_bg_time,valid_end_time,money_limit,coupon_money")->order($coupon_order)->select()->toArray();
            $data['giftbag_coupon_name_array'] = $giftbag_coupon_name_array;

            $return['new_list'][] =  $data;
        }

        unset($return['list']);
        $return['list'] = $return['new_list'];
        unset($return['new_list']);

        return $this->success($return);

    }
}
